<template>
  <el-tooltip effect="dark" placement="top" :enterable="true" :disabled="!showTooltip">
    <template slot="content">
      <div class="table-custom-tooltip" v-html="contentText"> </div>
    </template>
    <div class="text-overflow" ref="cell">
      <slot v-if="$slots.default"></slot>
      <template v-else>{{ content }}</template>
    </div>
  </el-tooltip>
</template>

<script>
export default {
  name: 'CustomTooltipNew',
  props: {
    content: String
  },
  data() {
    return {
      showTooltip: false,
      contentText: ''
    }
  },
  async mounted() {
    await this.$nextTick()

    const cellChild = this.$refs.cell
    if (!cellChild.childNodes.length) {
      this.showTooltip = false
      this.contentText = this.content
      return
    }
    // use range width instead of scrollWidth to determine whether the text is overflowing
    // to address a potential FireFox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1074543#c3
    const range = document.createRange()
    range.setStart(cellChild, 0)
    range.setEnd(cellChild, cellChild.childNodes.length)

    const rangeWidth = range.getBoundingClientRect().width
    const padding = 20
    this.contentText = [...cellChild.childNodes].map((item) => item.innerText || item.textContent).join(' ')

    if (this.contentText.startsWith('算法识别结果')) {
      this.contentText = this.contentText.replace('算法识别结果', '算法识别结果<br/>');
      this.contentText = this.contentText.replace('算法配置参数', '<br/>算法配置参数<br/>');
    }
    if (this.contentText.startsWith('算法配置参数')) {
      this.contentText = this.contentText.replace('算法配置参数', '算法配置参数<br/>');
    }
    this.showTooltip = rangeWidth + padding > cellChild.parentNode.offsetWidth
  }
}
</script>
<style lang="scss" scoped>
.text-overflow {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
<style>
.table-custom-tooltip {
  max-width: 600px !important;
  line-height: 20px;
  font-size: 14px;
}
</style>
